<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // 1. 旧存储工具（模拟历史代码，不可修改）
const OldStorage = {
  save: (key, value, success, fail) => {
    try {
      localStorage.setItem(key, value);
      console.log(success);
      success?.('保存成功');
    } catch (err) {
      fail?.(err.message);
    }
  },
  get: (key, success, fail) => {
    try {
      const value = localStorage.getItem(key);
      success?.(value);
    } catch (err) {
      fail?.(err.message);
    }
  }
};

// 2. 新存储工具（新实现，支持多存储类型+Promise）
const NewStorage = {
  // storageType: 'local' | 'session'
  save: (storageType, key, value) => {
    return new Promise((resolve, reject) => {
      try {
        const storage = storageType === 'session' ? sessionStorage : localStorage;
        storage.setItem(key, value);
        resolve('保存成功');
      } catch (err) {
        reject(err.message);
      }
    });
  },
  get: (storageType, key) => {
    return new Promise((resolve, reject) => {
      try {
        const storage = storageType === 'session' ? sessionStorage : localStorage;
        const value = storage.getItem(key);
        resolve(value);
      } catch (err) {
        reject(err.message);
      }
    });
  }
};

// 3. 适配器：适配OldStorage的调用格式到NewStorage
const OldStorageAdapter = {
  // 适配save方法：旧参数（key, value, success, fail）→ 内部调用新save（默认local）
  save: async (key, value, success, fail) => {
    try {
      const result = await NewStorage.save('local', key, value);
      success?.(result); // 回调旧接口的成功函数
    } catch (err) {
      fail?.(err); // 回调旧接口的失败函数
    }
  },
  // 适配get方法：同理
  get: async (key, success, fail) => {
    try {
      const value = await NewStorage.get('local', key);
      success?.(value);
    } catch (err) {
      fail?.(err);
    }
  }
};

// 4. 旧业务代码（无需修改，直接调用）
OldStorage.save = OldStorageAdapter.save;
OldStorage.get = OldStorageAdapter.get;

// 测试：旧调用方式仍可用，且实际用新存储工具
OldStorage.save('username', 'zhangsan', 
                (res) => console.log('旧调用成功：', res), // 输出：旧调用成功：保存成功
                (err) => console.log('旧调用失败：', err)
               );

OldStorage.get('username', 
               (val) => console.log('旧调用获取：', val), // 输出：旧调用获取：zhangsan
               (err) => console.log('旧调用失败：', err)
              );
NewStorage.save('local', 'username', 'lisi')
.then((res) => console.log('新调用成功：', res)) 

NewStorage.get('local', 'username')
.then((val) => console.log('新调用获取：', val))
    </script>
</body>
</html>